package com.beijiteshop.libcommon.base.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

/**
 * ViewModel基类
 */
open class BaseViewModel : ViewModel() {

    private val jobs = mutableListOf<Job>()

    val liveError = MutableLiveData<String?>()

    val liveEmpty = MutableLiveData<String?>()

    val liveNetError = MutableLiveData<String?>()

    /**
     * 协程 网络请求
     */
    protected fun launch(block: suspend CoroutineScope.() -> Unit) = viewModelScope.launch {
        block.invoke(this)
    }.addTo(jobs)

    override fun onCleared() {
        jobs.forEach { it.cancel() }
        super.onCleared()
    }
}

/**
 * 扩展函数，用于viewModel中的job 添加到list方便
 */
private fun Job.addTo(list: MutableList<Job>) {
    list.add(this)
}